from django.core.paginator import Paginator
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from api.models import Record, User
from xpinyin import Pinyin


def test():
    Record.objects.bulk_create()
    return None


def index(request):
    return render(request, 'api/index.html')


@csrf_exempt
def uploadFile(request):
    if request.method == 'POST':
        print(request.FILES)
        obj = request.FILES.get('file')
        print(request.FILES.get('InMemoryUploadedFile'))
    return HttpResponse('abc')


def response_as_json(data):
    return JsonResponse(data, safe=False)


def resopnse_ok(data, code=200, **kwargs):
    response = {
        'code': code,
        'msg': '成功',
        'data': list(data)
    }
    response.update(kwargs)
    print(response)
    return response_as_json(response)


def response_error(error_string, code=500, **kwargs):
    response = {
        'code': code,
        'msg': error_string,
        'data': {}
    }
    response.update(kwargs)
    print(response)
    return response_as_json(response)


ResponseOk = resopnse_ok
ResponseError = response_error


def get_user_list(request):
    users = User.objects.all().order_by('name_py').values()
    return ResponseOk(list(users))


def get_record_list(request):
    """
    请求所有的记录，通过用户名
    :param request:
    :return:
    """
    search = {}
    paginator = {}
    payed = request.GET.get('payed')
    name = request.GET.get('name')
    order_by = request.GET.get('order_by')
    if payed:
        search['payed'] = payed
    if name:
        search['user__name'] = name
    if order_by is None:
        order_by = ['payed', '-date']
    records = Record.objects.filter(**search) \
        .values('user__name', 'type', 'money', 'payed', 'date').order_by(*order_by)
    p = Paginator(records, 10)
    try:
        page = int(request.GET.get('page'))
        records = p.page(page)
    except:
        page = 1
        records = p.page(page)
    paginator['count'] = p.num_pages
    return ResponseOk(list(records), **paginator)


def update(request):
    try:
        user = User.objects.get(name='辉潮')
        return HttpResponse('存在')
    except User.DoesNotExist:
        user = User(name='辉潮', name_py='hc')
        user.save()
        return HttpResponse('成功')


def getPY(list):
    data = []
    p = Pinyin()
    for name in list:
        data.append({'name': name, 'name_py': p.get_initials(name, '')})
    return data


def updataUser(list):
    """
    更新用户表
    """
    data = getPY(list)
    for d in data:
        try:
            user = User.objects.get(name=d.get('name'))
        except User.DoesNotExist:
            user = User(name=d.get('name'), name_py=d.get('name_py'))
            user.save()
